<template>
	<a-button class="editable-add-btn" type="primary" style="margin-bottom: 8px; float: right"
		@click="handleAdd">Add</a-button>

	<a-table :dataSource="product" :columns="columns" bordered rowKey="id">
		<template #bodyCell="{ column, record }">
			<template v-if="column.dataIndex === 'operation'">
				<div class="editable-row-operations">
					<a-button type="primary" @click="handleEdit(record)">编辑</a-button>
					<a-button type="primary" danger style="margin-left: 4px" @click="handleDelete(record.id)">删除</a-button>
				</div>
			</template>
		</template>
	</a-table>

	<!-- 新增 / 编辑 抽屉 -->
	<a-drawer :width="500" :title="drawerTitle" :placement="placement" :open="open" @close="onClose">
		<template #extra>
			<a-button style="margin-right: 8px" type="primary" @click="onSubmit">Submit</a-button>
			<a-button v-if="isEdit" @click="resetForm">Reset</a-button>
		</template>

		<a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
			<a-form-item label="产品名称" name="product_name">
				<a-input v-model:value="formState.product_name" placeholder="请输入产品名称" />
			</a-form-item>
			<a-form-item label="产品描述" name="product_desc">
				<a-input v-model:value="formState.product_desc" placeholder="请输入产品描述" />
			</a-form-item>
			<a-form-item label="系统定义" name="system_def">
				<a-switch v-model:checked="formState.system_def" />
			</a-form-item>
		</a-form>
	</a-drawer>
</template>
  
<script setup>
import axios from 'axios'
import { Modal } from 'ant-design-vue'
import { ref, reactive, onMounted } from 'vue'

/* ---------- 基础变量 ---------- */
const open = ref(false)
const placement = ref('right')
const drawerTitle = ref('添加产品分类')
const isEdit = ref(false)
const editId = ref(null)
const product = ref([])

/* ---------- 表单 ---------- */
const formRef = ref()
const labelCol = { span: 5 }
const wrapperCol = { span: 13 }
const formState = reactive({
	product_name: '',
	product_desc: '',
	system_def: false
})
const rules = {
	product_name: [{ required: true, message: '请输入产品名称', trigger: ['blur', 'change'] }],
	product_desc: [{ required: true, message: '请输入产品描述', trigger: ['blur', 'change'] }]
}

/* ---------- 表格头 ---------- */
const columns = ref([
	{ title: '产品名称', dataIndex: 'product_name', key: 'product_name' },
	{ title: '产品描述', dataIndex: 'product_desc', key: 'product_desc' },
	{ title: '系统定义', dataIndex: 'system_def', key: 'system_def' },
	{ title: '创建时间', dataIndex: 'created_at', key: 'created_at' },
	{ title: '操作', dataIndex: 'operation', key: 'operation' }
])

/* ---------- 业务函数 ---------- */
const loadProduct = async () => {
	try {
		const res = await axios.get('http://127.0.0.1:3000/get-product')
		console.log('接口返回数据', res);
		product.value = res.data.data
	} catch (err) {
		console.log('接口返回异常', err)
	}
}

const handleAdd = () => {
	isEdit.value = false
	editId.value = null
	drawerTitle.value = '添加产品分类'
	open.value = true
}

const handleEdit = (row) => {
	isEdit.value = true
	editId.value = row.id
	drawerTitle.value = '编辑产品分类'
	// 回填
	formState.product_name = row.product_name
	formState.product_desc = row.product_desc
	formState.system_def = row.system_def === '是'
	open.value = true
}

const handleDelete = (id) => {
	if (!id) return
	Modal.confirm({
		title: '确定删除',
		content: '删除后不可恢复，是否继续？',
		okText: '确认',
		cancelText: '取消',
		onOk: async () => {
			try {
				await axios.delete(`http://127.0.0.1:3000/product/${id}`)
				await loadProduct()
			} catch (e) {
				console.error(e)
			}
		}
	})
}

const onSubmit = async () => {
	await formRef.value.validate()
	try {
		const payload = {
			product_name: formState.product_name,
			product_desc: formState.product_desc,
			system_def: formState.system_def
		}
		if (isEdit.value) {
			await axios.put(`http://127.0.0.1:3000/product/${editId.value}`, payload)
		} else {
			await axios.post('http://127.0.0.1:3000/add-product', payload)
		}
		await loadProduct()
		onClose()
	} catch (e) {
		console.error(e)
	}
}

const onClose = () => {
	open.value = false
	resetForm()
	isEdit.value = false
	editId.value = null
	drawerTitle.value = '添加产品分类'
}

const resetForm = () => {
	formRef.value?.resetFields()
}
const fetchAIResponse = async (message) => {
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer YOUR_API_KEY`,
    },
    body: JSON.stringify({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: message }],
    }),
  });
  const data = await response.json();
  console.log('AI Response:--', data);
  return data.choices[0].message.content;
};
/* ---------- 初始化 ---------- */
onMounted(() => {
	loadProduct(),
	fetchAIResponse()
})
</script>